package com.learn.springbootnetty.tcpdemo.长连接实现;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xiaodonghong
 * @description TODO
 * @date 2023/6/14-13:16
 */
public class MyRuns implements Runnable {
     Socket socket;
    BufferedReader reader;
    BufferedWriter writer;
    public MyRuns(Socket socket) {
        super();
        this.socket = socket;
    }
    @Override
    public void run() {
        Map<String, String> res = new HashMap<>();
        try {
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));//读取客户端消息
            writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));//向客户端写消息
            String mess = reader.readLine();
            System.out.println("接收的信息为:" + mess);
            if (mess != null && !"".equals(mess)) {
                Map<String, Object> readValue = JSONObject.parseObject(mess, Map.class);
                System.out.println(readValue.toString());
                String XXX= readValue.get("XXX").toString();
                res.put("res", String.valueOf(true));
            }
        } catch (Exception e) {
            e.printStackTrace();
            res.put("res", String.valueOf(false));
            res.put("msg", e.toString());
        } finally {
            try {
                System.out.println("运行结果：" + res);
                writer.write(JSONObject.toJSONString(res));
                writer.flush();
                if (reader != null) {
                    reader.close();
                }
                if (writer != null) {
                    writer.close();
                }
                if (socket != null) {
                    socket.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }
}